package com.sloth.util;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();


    /**
     * 将对象转换为json字符串
     * @param obj
     * @return
     */
    public static String object2Jsonstr(Object obj){
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;

    }


    /**
     * 将json字符串转化为对象
     * @param jsonStr
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T jsonStr2Object(String jsonStr,Class<T> clazz){
        try {
            return objectMapper.readValue(jsonStr.getBytes("UTF-8"),clazz);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * json字符串转换为list
     * @param jsonStr
     * @param beanType
     * @param <T>
     * @return
     */
    public static <T> List<T> json2List(String jsonStr,Class<T> beanType){
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class,beanType);
        try {
            List<T> list = objectMapper.readValue(jsonStr,javaType);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }










    public static JsonNode stringToJson(String str){
        try {
            return objectMapper.readTree(str);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
